﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
using UCL;

namespace SoIM.Server
{
    public partial class frmSrvMain : Form
    {
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>(); //用于保存所有通信客户端的Socket

        string clientName = null; //创建访问客户端的名字  
        IPAddress clientIP; //访问客户端的IP  
        int clientPort; //访问客户端的端口号  
        string strSRecMsg = null;

        Thread threadWatch = null; //负责监听客户端的线程  
        Socket socketWatch = null; //负责监听客户端的套接字  
        Socket socConnection = null;  //创建一个负责和客户端通信的套接字   

        AppDataHelper adh;
        public frmSrvMain()
        {
            InitializeComponent();
            //关闭对文本框的非法线程操作检查  
            RichTextBox.CheckForIllegalCrossThreadCalls = false;
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }

        private void frmSrvMain_Load(object sender, EventArgs e)
        {
            adh = new AppDataHelper();
            tbIp.Text = IPHelper.GetIPAddress();
            tbPort.Text = "6066";
        }

        private void btnStartSrv_Click(object sender, EventArgs e)
        {
            if (btnStartSrv.Text == "启动服务")
            {
                this.StartServer();
                btnStartSrv.Text = "停止服务";
            }
            else
            {
                socketWatch.Close();
                if (threadWatch != null) threadWatch.Abort();
                btnStartSrv.Text = "启动服务";
            }

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            //调用 ServerSendMsg方法  发送信息到客户端  
            ServerSendMsg(tbContent.Text.Trim());
        }

        /// <summary>
        /// 开始启动服务器
        /// </summary>
        private void StartServer()
        {
            //定义一个套接字用于监听客户端发来的信息  包含3个参数(IP4寻址协议,流式连接,TCP协议)  
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //服务端发送信息 需要1个IP地址和端口号  
            IPAddress ipaddress = IPAddress.Parse(tbIp.Text.Trim()); //获取文本框输入的IP地址  
            //将IP地址和端口号绑定到网络节点endpoint上   
            IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(tbPort.Text.Trim())); //获取文本框上输入的端口号  
            //监听绑定的网络节点  
            socketWatch.Bind(endpoint);
            //将套接字的监听队列长度限制为20  
            socketWatch.Listen(20);
            //创建一个监听线程   
            threadWatch = new Thread(WatchConnecting);
            //将窗体线程设置为与后台同步  
            threadWatch.IsBackground = true;
            //启动线程  
            threadWatch.Start();
            //启动线程后 tbMsgs文本框显示相应提示  
            tbMsgs.AppendText(string.Format("{0} 服务已启动，等待客户端连接!{1}", DateTime.Now, Environment.NewLine));
        }

        /// <summary>
        /// 监听客户端发来的请求  
        /// </summary> 
        private void WatchConnecting()
        {
            while (true)
            {
                try
                {
                    socConnection = socketWatch.Accept();
                }
                catch (Exception ex)
                {
                    tbMsgs.AppendText(ex.Message + Environment.NewLine); //提示套接字监听异常
                    break;
                }
                //获取访问客户端的IP
                clientIP = (socConnection.RemoteEndPoint as IPEndPoint).Address;
                //获取访问客户端的Port
                clientPort = (socConnection.RemoteEndPoint as IPEndPoint).Port;
                //创建访问客户端的唯一标识 由IP和端口号组成 
                clientName = string.Format("{0}:{1}", clientIP, clientPort);
                lstClients.Items.Add(clientName); //在客户端列表添加该访问客户端的唯一标识
                //adh.Insert("tLanUsers", "Name, IP, Face, Sign, State", string.Format("'{0}', '{1}', '{2}', '{3}', 1", "", clientIP + ":" + clientPort, "", ""));
                dicSocket.Add(clientName, socConnection); //将客户端名字和套接字添加到添加到数据字典中

                //创建通信线程 
                ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);
                Thread thread = new Thread(pts);
                thread.IsBackground = true;
                //启动线程
                thread.Start(socConnection);
                tbMsgs.AppendText(string.Format("{0} [{1}:{2}] 的客户端与您连接成功,现在你们可以开始通信了...{3}", DateTime.Now, clientIP, clientPort, Environment.NewLine));
            }
        }

        /// <summary>
        /// 发送信息到客户端的方法
        /// <para>服务端向客户端发送信息,在没有选择具体某个客户端的情况下,默认群发. 如果选择了具体某个客户端,则单独向该客户端发送信息.</para>
        /// </summary>
        /// <param name="sendMsg">发送的字符串信息</param>
        private void ServerSendMsg(string sendMsg)
        {
            if (socConnection == null)
            {
                tbMsgs.AppendText(string.Format("{0} 没有任何客户端连接到服务器!", DateTime.Now));
                return;
            }
            //将输入的字符串转换成 机器可以识别的字节数组
            byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendMsg);
            //向客户端列表选中的客户端发送信息
            if (!string.IsNullOrEmpty(lstClients.Text.Trim()))
            {
                //获得相应的套接字 并将字节数组信息发送出去
                dicSocket[lstClients.Text.Trim()].Send(arrSendMsg);
                //通过Socket的send方法将字节数组发送出去
                tbMsgs.AppendText(string.Format("{0} 您向[{1}:{2}]发送了：{4}{3}{4}", DateTime.Now, clientIP, clientPort, sendMsg, Environment.NewLine));
            }
            else //如果未选择任何客户端 则默认为群发信息
            {
                //遍历所有的客户端
                for (int i = 0; i < lstClients.Items.Count; i++)
                {
                    dicSocket[lstClients.Items[i].ToString()].Send(arrSendMsg);
                }
                if (!sendMsg.StartsWith("soimc-file:"))
                {
                    tbMsgs.AppendText(string.Format("{0} 您群发了信息:{2}{1}{2}", DateTime.Now, sendMsg, Environment.NewLine));
                }
            }
        }

        /// <summary>
        /// 接收客户端发来的信息
        /// </summary>
        /// <param name="socketClientPara">客户端套接字对象</param>
        private void ServerRecMsg(object socketClientPara)
        {
            Socket socketClient = socketClientPara as Socket;
            while (true)
            {
                int length = 0;
                //创建一个接收用的内存缓冲区 大小为10M字节数组
                byte[] arrServerRecMsg = new byte[10 * 1024 * 1024];
                try
                {
                    //获取接收的数据,并存入内存缓冲区  返回一个字节数组的长度
                    length = socketClient.Receive(arrServerRecMsg);
                }
                catch (SocketException ex)
                {
                    tbMsgs.AppendText(string.Format("{0} 套接字异常消息:{1}{2}", DateTime.Now, ex.Message, Environment.NewLine));
                    //如果套接字出现异常 很可能是对方客户端已经断开连接
                    tbMsgs.AppendText(string.Format("{0} [{1}:{2}] 已经与您断开连接{3}", DateTime.Now, clientIP, clientPort, Environment.NewLine));
                    dicSocket.Remove(clientName);//移除相应远程客户端的套接字 
                    lstClients.Items.Remove(clientName);//从客户端列表中移除该客户端 
                    break;
                }
                catch (Exception ex)
                {
                    tbMsgs.AppendText(string.Format("{0} 系统异常消息: {1}{2}", DateTime.Now, ex.Message, Environment.NewLine));
                    break;
                }
                //判断发送过来的数据是文件还是普通文字信息
                if (arrServerRecMsg[0] == 0) //0为文字信息
                {
                    //将字节数组 转换为人可以读懂的字符串
                    strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 1, length - 1);//真实有用的文本信息要比接收到的少1(标识符)
                    // 传输文件
                    if (strSRecMsg.StartsWith("soimc-file-send:"))
                    {
                        strSRecMsg = strSRecMsg.Substring(11);
                        actAddLinkLabel = new Action<string>(AddLinkLabel);
                        tbMsgs.Invoke(actAddLinkLabel, strSRecMsg);
                    }

                    //将接收到的信息附加到文本框txtMsg上  
                    tbMsgs.AppendText(string.Format("[{1}:{2}] {0} {4}{3}{4}", DateTime.Now, clientIP, clientPort, strSRecMsg, Environment.NewLine));
                }
                //如果发送过来的数据是文件
                if (arrServerRecMsg[0] == 1)
                {
                    //调用接受文件的方法
                    SaveFile(arrServerRecMsg, length - 1);//同样实际文件长度需要-1(减去标识符)
                }
            }
        }
        Action<string> actAddLinkLabel;
        private void AddLinkLabel(string filename)
        {
            tbMsgs.ScrollToCaret();
            LinkLabel lb = new LinkLabel() { Text = "[接收]", Tag = filename };
            lb.Location = tbMsgs.GetPositionFromCharIndex(tbMsgs.SelectionIndent);
            lb.Click += new EventHandler(lbGetFile_Click);
            tbMsgs.Controls.Add(lb);
        }

        /// <summary>
        /// 保存接收文件的方法 包含一个字节数组参数 和 文件的长度
        /// </summary>
        /// <param name="arrFile">字节数组参数</param>
        /// <param name="fileLength">文件的长度</param>
        private void SaveFile(byte[] arrFile, int fileLength)
        {
            SaveFileDialog sfDialog = new SaveFileDialog();
            //创建一个用于保存文件的对话框
            sfDialog = new SaveFileDialog();
            //获取文件名的后缀 比如文本文件后缀 .txt
            string fileNameSuffix = strSRecMsg.Substring(strSRecMsg.LastIndexOf("."));
            sfDialog.Filter = "(*" + fileNameSuffix + ")|*" + fileNameSuffix + ""; //文件类型
            sfDialog.FileName = strSRecMsg;  //文件名
            //如果点击了对话框中的保存文件按钮 
            if (sfDialog.ShowDialog(this) == DialogResult.OK)
            {
                string savePath = sfDialog.FileName; //获取文件的全路径
                //保存文件
                FileStream fs = new FileStream(savePath, FileMode.Create);
                //Write()方法需要传入3个参数,文件的字节数组,开始写入字节的索引位置以及字节数组的长度
                fs.Write(arrFile, 1, fileLength);
                string fName = savePath.Substring(savePath.LastIndexOf("\\") + 1); //文件名 不带路径
                string fPath = savePath.Substring(0, savePath.LastIndexOf("\\")); //文件路径 不带文件名
                tbMsgs.AppendText(string.Format("{0} 您成功接收了[{1}:{2}]发来的文件：{3}{5}保存路径：{4}{5}", DateTime.Now, clientIP, clientPort, fName, fPath, Environment.NewLine));
            }
        }

        private void tbMsgs_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            MessageBox.Show(e.LinkText);
        }
        private void lbGetFile_Click(object sender, EventArgs e)
        {
            string fn = ((LinkLabel)sender).Tag.ToString();
            ServerSendMsg(string.Format("soimc-file-save:{0}", fn));
        }
    }
}
